package com.property.demo.controller;

import com.property.demo.dto.ApiResponse;
import com.property.demo.dto.ParkingUsageDTO;
import com.property.demo.model.ParkingUsage;
import com.property.demo.service.ParkingUsageService;
import com.property.demo.util.DTOMapper;
import com.property.demo.util.SortUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/parking-usages")
public class ParkingUsageController {

    private static final Logger logger = LoggerFactory.getLogger(ParkingUsageController.class);

    @Autowired
    private ParkingUsageService parkingUsageService;

    /**
     * 获取所有车位使用记录
     */
    @GetMapping
    public ResponseEntity<?> getAllParkingUsages(
            @RequestParam(value = "page", defaultValue = "0") int page,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "sort", defaultValue = "id,desc") String sort) {
        try {
            Sort sortOrder = SortUtil.parseSort(sort);
            Pageable pageable = PageRequest.of(page, size, sortOrder);

            Page<ParkingUsage> parkingUsagesPage = parkingUsageService.findAll(pageable);
            List<ParkingUsageDTO> parkingUsageDTOs = DTOMapper.toParkingUsageDTOList(parkingUsagesPage.getContent());

            Map<String, Object> response = new HashMap<>();
            response.put("parkingUsages", parkingUsageDTOs);
            response.put("currentPage", parkingUsagesPage.getNumber());
            response.put("totalItems", parkingUsagesPage.getTotalElements());
            response.put("totalPages", parkingUsagesPage.getTotalPages());

            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("获取车位使用记录失败", e);
            return new ResponseEntity<>(
                new ApiResponse(false, "获取车位使用记录失败: " + e.getMessage()),
                HttpStatus.INTERNAL_SERVER_ERROR
            );
        }
    }

    /**
     * 根据ID获取车位使用记录
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getParkingUsageById(@PathVariable Long id) {
        try {
            ParkingUsage parkingUsage = parkingUsageService.findById(id);
            ParkingUsageDTO parkingUsageDTO = DTOMapper.toParkingUsageDTO(parkingUsage);
            return new ResponseEntity<>(parkingUsageDTO, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("获取车位使用记录失败", e);
            return new ResponseEntity<>(
                new ApiResponse(false, "获取车位使用记录失败: " + e.getMessage()),
                HttpStatus.NOT_FOUND
            );
        }
    }

    /**
     * 创建车位使用记录
     */
    @PostMapping
    public ResponseEntity<?> createParkingUsage(@RequestBody ParkingUsage parkingUsage) {
        try {
            logger.info("接收到创建车位使用记录请求: {}", parkingUsage);

            // 检查是否是前端提交的嵌套对象结构
            if (parkingUsage.getParking() != null && parkingUsage.getParking().getId() != null &&
                parkingUsage.getOwner() != null && parkingUsage.getOwner().getId() != null) {

                logger.info("检测到嵌套对象结构，正在处理...");
                // 嵌套对象结构已经符合后端模型要求，无需额外处理

                // 记录关键字段信息
                logger.info("车位ID: {}", parkingUsage.getParking().getId());
                logger.info("业主ID: {}", parkingUsage.getOwner().getId());
                if (parkingUsage.getVehicle() != null) {
                    logger.info("车辆ID: {}", parkingUsage.getVehicle().getId());
                }
                logger.info("使用类型: {}", parkingUsage.getUsageType());
                logger.info("开始日期: {}", parkingUsage.getStartDate());
                logger.info("结束日期: {}", parkingUsage.getEndDate());
                logger.info("费用: {}", parkingUsage.getFee());
                logger.info("支付状态: {}", parkingUsage.getPaymentStatus());
            } else {
                logger.warn("接收到的数据不符合预期的嵌套对象结构，可能导致保存失败");
            }

            ParkingUsage savedParkingUsage = parkingUsageService.save(parkingUsage);
            ParkingUsageDTO parkingUsageDTO = DTOMapper.toParkingUsageDTO(savedParkingUsage);

            logger.info("车位使用记录创建成功，ID: {}", savedParkingUsage.getId());

            return new ResponseEntity<>(
                new ApiResponse(true, "车位使用记录创建成功", parkingUsageDTO),
                HttpStatus.CREATED
            );
        } catch (Exception e) {
            logger.error("创建车位使用记录失败", e);
            return new ResponseEntity<>(
                new ApiResponse(false, "创建车位使用记录失败: " + e.getMessage()),
                HttpStatus.BAD_REQUEST
            );
        }
    }

    /**
     * 更新车位使用记录
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateParkingUsage(
            @PathVariable Long id,
            @RequestBody ParkingUsage parkingUsage) {
        try {
            ParkingUsage updatedParkingUsage = parkingUsageService.update(id, parkingUsage);
            ParkingUsageDTO parkingUsageDTO = DTOMapper.toParkingUsageDTO(updatedParkingUsage);
            return new ResponseEntity<>(
                new ApiResponse(true, "车位使用记录更新成功", parkingUsageDTO),
                HttpStatus.OK
            );
        } catch (Exception e) {
            logger.error("更新车位使用记录失败", e);
            return new ResponseEntity<>(
                new ApiResponse(false, "更新车位使用记录失败: " + e.getMessage()),
                HttpStatus.BAD_REQUEST
            );
        }
    }

    /**
     * 删除车位使用记录
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteParkingUsage(@PathVariable Long id) {
        try {
            parkingUsageService.delete(id);
            return new ResponseEntity<>(
                new ApiResponse(true, "车位使用记录删除成功"),
                HttpStatus.OK
            );
        } catch (Exception e) {
            logger.error("删除车位使用记录失败", e);
            return new ResponseEntity<>(
                new ApiResponse(false, "删除车位使用记录失败: " + e.getMessage()),
                HttpStatus.BAD_REQUEST
            );
        }
    }

    /**
     * 根据小区ID获取车位使用记录
     */
    @GetMapping("/community/{communityId}")
    public ResponseEntity<?> getParkingUsagesByCommunityId(
            @PathVariable Long communityId,
            @RequestParam(value = "page", defaultValue = "0") int page,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "sort", defaultValue = "id,desc") String sort) {
        try {
            Sort sortOrder = SortUtil.parseSort(sort);
            Pageable pageable = PageRequest.of(page, size, sortOrder);

            Page<ParkingUsage> parkingUsagesPage = parkingUsageService.findByCommunityId(communityId, pageable);
            List<ParkingUsageDTO> parkingUsageDTOs = DTOMapper.toParkingUsageDTOList(parkingUsagesPage.getContent());

            Map<String, Object> response = new HashMap<>();
            response.put("parkingUsages", parkingUsageDTOs);
            response.put("currentPage", parkingUsagesPage.getNumber());
            response.put("totalItems", parkingUsagesPage.getTotalElements());
            response.put("totalPages", parkingUsagesPage.getTotalPages());

            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("获取小区车位使用记录失败", e);
            return new ResponseEntity<>(
                new ApiResponse(false, "获取小区车位使用记录失败: " + e.getMessage()),
                HttpStatus.INTERNAL_SERVER_ERROR
            );
        }
    }

    /**
     * 根据车位ID获取使用记录
     */
    @GetMapping("/parking/{parkingId}")
    public ResponseEntity<?> getParkingUsagesByParkingId(@PathVariable Long parkingId) {
        try {
            List<ParkingUsage> parkingUsages = parkingUsageService.findByParkingId(parkingId);
            List<ParkingUsageDTO> parkingUsageDTOs = DTOMapper.toParkingUsageDTOList(parkingUsages);
            return new ResponseEntity<>(parkingUsageDTOs, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("获取车位使用记录失败", e);
            return new ResponseEntity<>(
                new ApiResponse(false, "获取车位使用记录失败: " + e.getMessage()),
                HttpStatus.INTERNAL_SERVER_ERROR
            );
        }
    }

    /**
     * 根据业主ID获取使用记录
     */
    @GetMapping("/owner/{ownerId}")
    public ResponseEntity<?> getParkingUsagesByOwnerId(@PathVariable Long ownerId) {
        try {
            List<ParkingUsage> parkingUsages = parkingUsageService.findByOwnerId(ownerId);
            List<ParkingUsageDTO> parkingUsageDTOs = DTOMapper.toParkingUsageDTOList(parkingUsages);
            return new ResponseEntity<>(parkingUsageDTOs, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("获取业主车位使用记录失败", e);
            return new ResponseEntity<>(
                new ApiResponse(false, "获取业主车位使用记录失败: " + e.getMessage()),
                HttpStatus.INTERNAL_SERVER_ERROR
            );
        }
    }

    /**
     * 根据车辆ID获取使用记录
     */
    @GetMapping("/vehicle/{vehicleId}")
    public ResponseEntity<?> getParkingUsagesByVehicleId(@PathVariable Long vehicleId) {
        try {
            List<ParkingUsage> parkingUsages = parkingUsageService.findByVehicleId(vehicleId);
            List<ParkingUsageDTO> parkingUsageDTOs = DTOMapper.toParkingUsageDTOList(parkingUsages);
            return new ResponseEntity<>(parkingUsageDTOs, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("获取车辆停车记录失败", e);
            return new ResponseEntity<>(
                new ApiResponse(false, "获取车辆停车记录失败: " + e.getMessage()),
                HttpStatus.INTERNAL_SERVER_ERROR
            );
        }
    }

    /**
     * 高级搜索
     */
    @GetMapping("/search")
    public ResponseEntity<?> searchParkingUsages(
            @RequestParam(required = false) Long communityId,
            @RequestParam(required = false) Long parkingId,
            @RequestParam(required = false) Long ownerId,
            @RequestParam(required = false) String ownerName,
            @RequestParam(required = false) String licensePlate,
            @RequestParam(required = false) String usageType,
            @RequestParam(required = false) String paymentStatus,
            @RequestParam(value = "page", defaultValue = "0") int page,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "sort", defaultValue = "id,desc") String sort) {
        try {
            Map<String, Object> params = new HashMap<>();

            if (communityId != null) params.put("communityId", communityId);
            if (parkingId != null) params.put("parkingId", parkingId);
            if (ownerId != null) params.put("ownerId", ownerId);
            if (ownerName != null) params.put("ownerName", ownerName);
            if (licensePlate != null) params.put("licensePlate", licensePlate);
            if (usageType != null) params.put("usageType", usageType);
            if (paymentStatus != null) params.put("paymentStatus", paymentStatus);

            Sort sortOrder = SortUtil.parseSort(sort);
            Pageable pageable = PageRequest.of(page, size, sortOrder);

            Page<ParkingUsage> parkingUsagesPage = parkingUsageService.search(params, pageable);
            List<ParkingUsageDTO> parkingUsageDTOs = DTOMapper.toParkingUsageDTOList(parkingUsagesPage.getContent());

            Map<String, Object> response = new HashMap<>();
            response.put("parkingUsages", parkingUsageDTOs);
            response.put("currentPage", parkingUsagesPage.getNumber());
            response.put("totalItems", parkingUsagesPage.getTotalElements());
            response.put("totalPages", parkingUsagesPage.getTotalPages());

            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("搜索车位使用记录失败", e);
            return new ResponseEntity<>(
                new ApiResponse(false, "搜索车位使用记录失败: " + e.getMessage()),
                HttpStatus.INTERNAL_SERVER_ERROR
            );
        }
    }
}
